﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using CommunityToolkit.Mvvm.Messaging;
using MauiControl.Models;
using MauiControl.Services;
using MauiControl.Views;
using Newtonsoft.Json;

namespace MauiControl.ViewModels
{
    public class DeviceSearchPageViewModel : INotifyPropertyChanged
    {
        private string _deviceName = "Z";
        private ObservableCollection<BleDeviceInfo> _deviceList;
        private BleDeviceInfo _selectedDevice;
        private readonly BluetoothService _bluetoothService;
        private readonly INavigationService _navigationService;
        private CancellationTokenSource _cancellationTokenSource;
        private bool _isSearching;

        public DeviceSearchPageViewModel(BluetoothService bluetoothService, INavigationService navigationService)
        {
            _bluetoothService = bluetoothService ?? throw new ArgumentNullException(nameof(bluetoothService));
            _navigationService = navigationService ?? throw new ArgumentNullException(nameof(navigationService));

            _deviceList = new ObservableCollection<BleDeviceInfo>();

            SearchDeviceCommand = new Command(async () => await SearchDeviceAsync());
            StopSearchCommand = new Command(StopSearch);
            ConnectDeviceCommand = new Command<BleDeviceInfo>(async (device) => await ConnectDeviceAsync(device));
            ContinueDeviceCommand = new Command(async () => await ConnectDeviceAsync(SelectedDevice), () => SelectedDevice != null);
        }

        public string DeviceName
        {
            get => _deviceName;
            set
            {
                if (_deviceName != value)
                {
                    _deviceName = value;
                    OnPropertyChanged();
                }
            }
        }

        public ObservableCollection<BleDeviceInfo> DeviceList
        {
            get => _deviceList;
            set
            {
                if (_deviceList != value)
                {
                    _deviceList = value;
                    OnPropertyChanged();
                }
            }
        }

        public bool IsSearching
        {
            get => _isSearching;
            set
            {
                if (_isSearching != value)
                {
                    _isSearching = value;
                    OnPropertyChanged();
                }
            }
        }

        public BleDeviceInfo SelectedDevice
        {
            get => _selectedDevice;
            set
            {
                if (_selectedDevice != value)
                {
                    _selectedDevice = value;
                    OnPropertyChanged();
                    ContinueDeviceCommand.ChangeCanExecute(); // 更新按钮状态
                }
            }
        }

        public ICommand SearchDeviceCommand { get; }
        public ICommand StopSearchCommand { get; }
        public ICommand ConnectDeviceCommand { get; }
        public Command ContinueDeviceCommand { get; }

        private async Task SearchDeviceAsync()
        {
            if (IsSearching) return;

            // 清空设备列表
            DeviceList.Clear();
            IsSearching = true;

            _cancellationTokenSource = new CancellationTokenSource();
            _cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10)); // 20秒后自动取消

            try
            {
                var devices = await _bluetoothService.SearchDevicesAsync(_cancellationTokenSource.Token, OnDeviceAdded);
            }
            catch (OperationCanceledException)
            {
                // 不再弹出提示窗口
            }
            catch (Exception ex)
            {
                await App.Current.MainPage.DisplayAlert("Error", ex.Message, "OK");
            }
            finally
            {
                IsSearching = false;
                _cancellationTokenSource?.Dispose();
                _cancellationTokenSource = null;
            }
        }

        private void OnDeviceAdded(BleDeviceInfo device)
        {
            if (string.IsNullOrEmpty(DeviceName) ||
                device.DeviceName.Contains(DeviceName, StringComparison.OrdinalIgnoreCase))
            {
                if (!DeviceList.Any(d => d.DeviceAddress == device.DeviceAddress))
                {
                    MainThread.InvokeOnMainThreadAsync(() => DeviceList.Add(device));
                }
            }
        }

        private void StopSearch()
        {
            _cancellationTokenSource?.Cancel();
            IsSearching = false;
        }

        private async Task ConnectDeviceAsync(BleDeviceInfo device)
        {
            if (device == null) return;

            try
            {
                var connectedDeviceInfo = await _bluetoothService.ConnectDeviceAsync(device.DeviceAddress);

                // 发送设备连接消息
                WeakReferenceMessenger.Default.Send(connectedDeviceInfo);

                // 导航到 MainPage
                await Shell.Current.GoToAsync($"///MainPage");
            }
            catch (Exception ex)
            {
                await App.Current.MainPage.DisplayAlert("Error", $"连接设备失败: {ex.Message}", "OK");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}